//
//  NetworkTools.swift
//  weiboLQ
//
//  Created by 半缘君 on 15/12/7.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
import AFNetworking

private let ERROR_NIL_TOKEN = NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"])

typealias RequestCallBack = (result:AnyObject?, error:NSError?) -> Void

enum LQRequestMethod:String{
    case GET = "get"
    case POST = "post"
}

class NetworkTools: AFHTTPSessionManager {
    
    private let appKey = "1264679855"
    private let appSecret = "656f08154c4cc5b0605c5134a75f85fc"
//    private let appKey = "3863118655"
//    private let appSecret = "b94c088ad2cdae8c3b9641852359d28c"
    private let redirectUri = "http://www.baidu.com"
    
    /// 单例
    static let shareNetworkTools:NetworkTools = {
        let tool = NetworkTools(baseURL: nil)
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    
    /// 返回 token 字典
//    private var tokenDict: [String: AnyObject]? {
//        // 判断 token 是否有效
//        if let token = UserAccountViewModel.shareAccountModel.accountToken {
////            print("token" + token)
//            return ["access_token": token]
//        }
//        
//        return nil
//    }
}

//发送微博
extension NetworkTools {
    
    
    //文字
    //url
    //parameter
    //finish
    func sentStatus (status:String,image:UIImage?,finished:(result:AnyObject?, error:NSError?) -> Void) {
        
        var parameters:[String:AnyObject]?
        
        if !appendToken(&parameters) {
            finished(result: nil, error: ERROR_NIL_TOKEN)
            return
        }
            parameters!["status"] = status
        
        // 3. 判断是否上传图片
        if image == nil {
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            tokenRequest(.POST, URLString: urlString, parameters: parameters, finished: finished)
        } else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let data = UIImagePNGRepresentation(image!)
            
            upload(urlString, data: data!, name: "pic", parameters: parameters, finished: finished)
        }

    }
}

//App Key：1264679855
//App Secret：656f08154c4cc5b0605c5134a75f85fc
//授权回调页：http://www.baidu.com
//MARK: - 用户信息相关
extension NetworkTools {
    
    func loadStatus (since_ID since_id:Int,max_id:Int,finished:(result:AnyObject?,error:NSError?) -> ()) {
    let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //access_token=2.00XFnoyCLATa4B548ed321cf1eD_9E
        // 1. 获取 token 字典
        var parameter = [String:AnyObject]?()
        if !appendToken(&parameter){
            // token 无效
            finished(result: nil, error: ERROR_NIL_TOKEN)
            return
        }
        if since_id > 0 {
            parameter!["since_id"] = since_id
        } else if max_id > 0 {
            parameter!["max_id"] = max_id - 1
        }
        tokenRequest(.GET, URLString: urlString, parameters: parameter, finished: finished)
}
}


// MARK: - OAuth 相关方法
extension NetworkTools {
    //请求授权页面URL
//    client_id	true	string	申请应用时分配的AppKey。
//    redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址
    var oauthURL:NSURL {
        return NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUri)")!
    }
    
    //client_id	true	string	申请应用时分配的AppKey。
//    client_secret	true	string	申请应用时分配的AppSecret。
//    grant_type	true	string	请求的类型，填写authorization_code
//    
//    grant_type为authorization_code时
//    必选	类型及范围	说明
//    code	true	string	调用authorize获得的code值。
//    redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
    //根据授权码code发送请求得到令牌Token
    /// -see:[https://api.weibo.com/oauth2/access_token](https://api.weibo.com/oauth2/access_token)
    func loadAccessToken (code:String,finished:(result:AnyObject?, error:NSError?) -> Void) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id":appKey,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUri
        ]
        request(LQRequestMethod.POST, URLString: urlString, parameters: params, finished: finished)
    }
    /// 加载信息
/// -see:[https://api.weibo.com/2/users/show.json](https://api.weibo.com/2/users/show.json)
    func loadUserInfo (userAccount:UserAccountModel,finished:(result: AnyObject?, error: NSError?) -> Void) {
        
        let URLString = "https://api.weibo.com/2/users/show.json"
//        access_token	false	string	采用OAuth授权方式为必填参数
//        uid	false	int64	需要查询的用户ID。
//        screen_name	false	string	需要查询的用户昵称。
        let param:[String:AnyObject] = [
        "access_token": userAccount.access_token!,
        "uid": userAccount.uid!
        ]
        
        request(.GET, URLString: URLString, parameters: param, finished: finished)
    }
    
    
}


// MARK: - 封装网络请求
extension NetworkTools {
    
    private func appendToken(inout parameters: [String: AnyObject]?) -> Bool {
        guard let token = UserAccountViewModel.shareAccountModel.accountToken else {
            return false
        }
        // 2> 判断参数字典是否有值
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        // 3> 设置 token
        parameters!["access_token"] = token
        
        return true
    }
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  地址
    /// - parameter parameters: 参数
    /// - parameter finished:   回调
    private func tokenRequest (method:LQRequestMethod,URLString:String,var parameters:[String:AnyObject]?,finished:(result:AnyObject?, error:NSError?) -> Void) {
        
       
        // 1> 如果追加 token 失败，直接返回
        if !appendToken(&parameters){
            // token 无效
            finished(result: nil, error:ERROR_NIL_TOKEN)
            return
        }
        
        
        request(method, URLString: URLString, parameters: parameters!, finished: finished)

    }
    
    /// 网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  地址
    /// - parameter parameters: 参数
    /// - parameter finished:   回调
    private func request(method:LQRequestMethod,URLString:String,parameters:[String:AnyObject]?,finished:(result:AnyObject?, error:NSError?) -> Void){
        
        let success:((NSURLSessionDataTask,AnyObject) -> ())? = {
            (task:NSURLSessionDataTask,result: AnyObject) -> ()
            in
            
            finished(result: result, error: nil)
        }
        
        let failure:((NSURLSessionDataTask?,NSError) -> ())? = {
            (task:NSURLSessionDataTask?, error:NSError) -> Void
            in
            finished(result: nil, error: error)
            
        }
        
        if method == .GET{

            GET(URLString, parameters: parameters, success:success, failure:failure)
        } else if method == .POST{
            POST(URLString, parameters: parameters, success: success, failure: failure)
        }
    }
    /// 上传文件
    ///
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数
    /// - parameter finished:   完成回调
   func upload(URLString:String, data: NSData, name: String,var  parameters:[String:AnyObject]?,finished:(result:AnyObject?, error:NSError?) -> ()) {
    // 1. 获取 token 字典
    if !appendToken(&parameters){
        finished(result: nil,error: ERROR_NIL_TOKEN)
        return
    }
    
      POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
        
         formData.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
        
        }, success: { (_, result) -> Void in
            finished(result:result,error:nil)
        }) { (_, error) -> Void in
            print(error)
            finished(result: nil, error: error)
    }
    }
}
